<template>
  <div>
    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
      @close="close"
    >
      <h3 v-if="crmcustomer__name !== undefined">客户:{{ crmcustomer__name }}的询盘订单</h3>
      <el-form :model="temp" label-position="left" label-width="80px">
        <el-form-item label="客户ID" prop="name">
          <el-input v-model="temp.crmcustomer_id" disabled />
        </el-form-item>
        <el-form-item label="订单名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入订单名称" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="temp.crmorderstate_id"
            filterable
            clearable
            reserve-keyword
            placeholder="选择订单状态"
          >
            <el-option
              v-for="item in orderStates"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户需求">
          <el-input v-model="temp.quote" type="textarea" />
        </el-form-item>
      </el-form>
      <div v-if="ai_replay.length" style="max-height: 200px; overflow-y: auto;" v-html="ai_replay" />
      <aireply v-if="mailbox_data" :type="aireply_type" :mailbox_id="mailbox_data.id" @success="handleInsertReplay" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Post, Put, Delete } from '@/api/crm/crmorder'
import { Get as GetOrderStatus } from '@/api/crm/crmorderstate'
import { countries, customer_source, getCountryLabel } from '../../../api/crm/crmcommon'
import Aireply from './aireply'
export default {
  name: 'Crmneworder',
  components: { Aireply },
  props: ['crmcustomer_id', 'crmcustomer__name', 'mailbox_data', 'isVisible'],
  data() {
    return {
      aireply_type: 'quote_summary',
      ai_replay: '',
      inputVisible: false,
      inputValue: '',
      data: [],
      listLoading: false,
      getCountryLabel: getCountryLabel,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      countries: countries,
      orderStates: [],
      customer_sources: customer_source,
      action: 'create',
      dialogVisible: false,
      title: '',
      customer: undefined,
      temp: {
        name: '',
        manager: this.$store.getters.fullname,
        ending_date: '',
        crmcustomer_id: '',
        order_no: '',
        trade_type: '',
        invoice_number: '',
        crmorderstate_id: '',
        currency: 'USD',
        quote: ''
      },
      width: '',
      orderstatesloading: false,
      innerDialogVisible: false
    }
  },
  watch: {
    isVisible(v) {
      this.innerDialogVisible = v
      this.temp.crmcustomer_id = this.crmcustomer_id
      console.log(this.temp.crmcustomer_id)
      this.handleAction(this.action, '新增询盘订单')
    }
  },
  created() {
    this.handleGetOrderState()
  },
  methods: {
    handleInsertReplay(data) {
      this.ai_replay = data
      // eslint-disable-next-line no-empty-character-class
      const jsonMatch = data.match(/{[\s\S]*}/)
      if (jsonMatch) {
        const jsonString = jsonMatch[0]
        // 解析 JSON 字符串为对象
        let jsonData
        try {
          jsonData = JSON.parse(jsonString)
        } catch (error) {
          console.error('Invalid JSON string:', error)
        }

        // 提取 query 字段
        if (jsonData && jsonData.query) {
          this.temp.quote = jsonData.query
          this.temp.name = jsonData.name
        } else {
          console.error('Query field not found in JSON data')
        }
      } else {
        console.error('No JSON string found in the text')
      }
    },
    handleClose(tag) {
      this.temp.tag.splice(this.temp.tag.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleGetOrderState() {
      this.orderstatesloading = true
      GetOrderStatus().then(response => {
        this.orderStates = response.data.data.reverse()
        if (this.orderStates !== undefined && this.orderStates) {
          // 找到index最小的状态作为默认值
          const minIndexState = this.orderStates.reduce((min, current) => {
            return current.index < min.index ? current : min
          })
          this.temp.crmorderstate_id = minIndexState.id
        }
        this.orderstatesloading = false
      }).catch(err => {
        console.log(err)
        this.orderstatesloading = false
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.temp.tag.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    close() {
      this.$emit('close', true)
    },
    resetTemp() {
      this.temp = {
        name: '',
        manager: this.$store.getters.fullname,
        ending_date: '',
        order_no: '',
        trade_type: '',
        invoice_number: '',
        crmorderstate_id: '',
        currency: 'USD',
        quote: ''
      }
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '添加新询盘订单'
          // this.resetTemp()
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除询盘:${row.name}?`
          this.temp = Object.assign({}, row)
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改询盘:${row.name}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(_data
          ).then(response => {
            this.notify('添加成功')
            this.innerDialogVisible = false
            this.mailbox_data.crmorder_info = response.data
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
